package com.dada.tiku.web.filter;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 微信API工具类
 * @author binxiao
 *
 */
public class QyWxUtils {

	//企业ID
	public static String corpid = "wwc24e0d729fd2357e1";
	
	//企业应用ID
	public static String agentId = "10000032";
	
	//企业开发秘钥
	public static String secret = "qGG7lw7q1r9x-2L4o6X2GLx9NMvkLDj7xPiJRYbWuxU1";
	
	/**
	 * 获取企业微信的access_token
	 * @return
	 * @throws Exception 
	 */
	public static String getAccessToken() throws Exception {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+QyWxUtils.corpid+"&corpsecret="+QyWxUtils.secret;
		return getDataFromWx(url);
	}
	
	/**
	 * 利用get方式从微信那里获得数据
	 * @param url
	 * @return
	 */
	public static String getDataFromWx(String url) throws Exception {
		URL u = new URL(url);
//		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		URLConnection conn = u.openConnection();
		//可以设置方法类型,设置连接超时时间等
		//conn.setRequestMethod("get");
		
		InputStream in = conn.getInputStream();
		InputStreamReader isr = new InputStreamReader(in);
		
		//创建缓存流,主要提高效率
		BufferedReader br  = new BufferedReader(isr);
		StringBuilder sb = new StringBuilder();
		String aLine = null;
		while((aLine=br.readLine())!=null) {
			sb.append(aLine);
		}
		br.close();
		return sb.toString();
	}
	
	/**
	 * 获取用户信息
	 * @param accessToken
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	public static String getUserInfo(String accessToken,String code) throws Exception {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken+"&code="+code;
		return getDataFromWx(url);
	}
	
	public static void main(String[] args) throws Exception {
		System.err.println(getAuth());
	}
	public static String getAuth() throws Exception {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwc24e0d729fd2357e&redirect_uri=http://binxiao.mingmaoxinxi.com:8080/keda/keda/find_trouble.html&response_type=code&scope=SCOPE&agentid=1000003&state=STATE#wechat_redirect";
		return getDataFromWx(url);
	}
}